/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.adama.controller;

import fr.adama.dto.ModeleFactureDTO;
import fr.adama.entite.modele.ModeleFacture;
import fr.adama.service.ModeleFactureService;
import fr.adama.validator.ModeleFactureValidator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author mini-john
 */
@Controller
public class ModeleFactureController {

    private static final Logger logger = LoggerFactory.getLogger(ModeleFactureController.class);

    @Autowired
    private MessageSource messageSource;
    @Autowired
    ModeleFactureService modeleFactureService;

    @RequestMapping(method = RequestMethod.GET, value = "/modele/facture/index.do")
    public ModelAndView index() {
        return new ModelAndView("modele/facture/index");
    }

    @RequestMapping(method = RequestMethod.GET, value = "/modele/facture/add.do")
    public String add(ModelMap model) {

        ModeleFactureDTO modelefacture = new ModeleFactureDTO();
        model.addAttribute("modelfacture", modelefacture);
        return "modele/facture/add";
    }
    @RequestMapping(method = RequestMethod.POST, value = "/modele/facture/add.do")
    public ModelAndView insertModelPaie(@ModelAttribute("modelfacture") ModeleFactureDTO modelfacture, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {

        result = new BeanPropertyBindingResult(modelfacture, "modelfacture");

        ModeleFactureValidator validator = new ModeleFactureValidator(messageSource);
        validator.validate(modelfacture, result);
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            map.put("modelfacture", modelfacture);
            map.put("org.springframework.validation.BindingResult.modelfacture", result);
            return new ModelAndView("modele/facture/add", map);
        }
        try {
            logger.info("Ajout du model de paie {}", modelfacture.getNom());
            modelfacture = modeleFactureService.addModelFacture(modelfacture);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("ModelFacture.add.success", new String[]{modelfacture.getNom()}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
               logger.error("Erreur d'ajout du model de facture {}", modelfacture.getNom(),ex);
               logger.error(""+ex.getCause());
            if (ex.getCause() instanceof ConstraintViolationException) {
                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("NOMEXISTMODELEFACTURE")) {
                    ObjectError error = new ObjectError("nom", messageSource.getMessage("ModelFacture.add.error.model.exist", new String[]{modelfacture.getNom()}, new Locale("fr")));
                    result.addError(error);
                    Map<String, Object> map = new HashMap<>();
                    map.put("modelfacture", modelfacture);
                    map.put("org.springframework.validation.BindingResult.modelfacture", result);
                    return new ModelAndView("modele/facture/add", map);
                }

            } 
        }
        return new ModelAndView("redirect:/modele/facture/show.do", "id", modelfacture.getId());
    }
    @RequestMapping(method = RequestMethod.GET, value = "/modele/facture/list.do")
    public ModelAndView listModele() {
        List<ModeleFactureDTO> listModel = modeleFactureService.findAll(ModeleFacture.class, ModeleFactureDTO.class);
        return new ModelAndView("modele/facture/list", "listModel", listModel);

    }

    @RequestMapping(method = RequestMethod.GET, value = "/modele/facture/show.do")
    public ModelAndView getModelById(@RequestParam(required = true, value = "id") Long id) {
        ModeleFactureDTO modelFacture = modeleFactureService.getById(id, ModeleFacture.class, ModeleFactureDTO.class);

        return new ModelAndView("modele/facture/show", "modelfacture", modelFacture);
    }
    
     @RequestMapping(method = RequestMethod.GET, value = "/modele/facture/update.do")
    public ModelAndView getModelForUpdate(@RequestParam(required = true, value = "id") Long id) {
       ModeleFactureDTO modelFacture = modeleFactureService.getById(id, ModeleFacture.class, ModeleFactureDTO.class);

        return new ModelAndView("modele/facture/update", "modelfacture", modelFacture);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/modele/facture/update.do")
    public ModelAndView updateModelPaie(@ModelAttribute("modelfacture") ModeleFactureDTO modelFacture, BindingResult result, RedirectAttributes redirectAttributes, Locale locale) {

        result = new BeanPropertyBindingResult(modelFacture, "modelpaie");

        ModeleFactureValidator validator = new ModeleFactureValidator(messageSource);
        validator.validate(modelFacture, result);
        if (result.hasErrors()) {
            Map<String, Object> map = new HashMap<>();
            map.put("modelfacture", modelFacture);
            map.put("org.springframework.validation.BindingResult.modelfacture", result);
            return new ModelAndView("modele/facture/update", map);
        }
        try {
             logger.info("Mis à jour du model de facture {}", modelFacture.getNom());
            modelFacture = modeleFactureService.updateModelFacture(modelFacture);
            redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("ModelFacture.update.success", new String[]{modelFacture.getNom()}, new Locale("fr")));
        } catch (DataIntegrityViolationException ex) {
            logger.error("Erreur de mis à jour du model de paie {}", modelFacture.getNom(),ex);
            if (ex.getCause() instanceof ConstraintViolationException) {
                ConstraintViolationException cdts = (ConstraintViolationException) ex.getCause();
                if (cdts.getConstraintName().equalsIgnoreCase("NOMEXISTMODELPAIE")) {
                    ObjectError error = new ObjectError("nom", messageSource.getMessage("ModelFacturee.update.error.model.exist", new String[]{modelFacture.getNom()}, new Locale("fr")));
                    result.addError(error);
                    Map<String, Object> map = new HashMap<>();
                    map.put("modelfacture", modelFacture);
                    map.put("org.springframework.validation.BindingResult.modelpaie", result);
                    return new ModelAndView("modele/facture/update", map);
                }

            } 
        }
        return new ModelAndView("redirect:/modele/facture/show.do", "id", modelFacture.getId());
    }
}
